package com.xh.demo.commons.model.response;

import com.xh.demo.commons.enums.MessageEnum;
import com.xh.demo.commons.message.CommonMessage;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;

/**
 * @author wen
 * @apiNote API全局返回结果类
 * @since 2021-12-11
 */
@NoArgsConstructor
@AllArgsConstructor
public class R<T> implements CommonMessage {

    private int code;

    private String msg;

    private T data;

    private long timestamp;

    private R(CommonMessage message, T data) {
        this.code = message.getCode();
        this.msg = message.getMsg();
        this.timestamp = System.currentTimeMillis();
        this.data = data;
    }

    private R(String msg, CommonMessage message) {
        this.code = message.getCode();
        this.msg = message.getMsg();
        this.timestamp = System.currentTimeMillis();
    }

    public static <T> R<T> success() {
        return build(MessageEnum.SUCCESS, null);
    }

    public static <T> R<T> success(T data) {
        return build(MessageEnum.SUCCESS, data);
    }

    public static <T> R<T> failed() {
        return build(MessageEnum.FAILED, null);
    }

    public static <T> R<T> failed(T data) {
        return build(MessageEnum.FAILED, data);
    }

    public static <T> R<T> res(int res) {
        return res > 0 ? success() : failed();
    }

    public static <T> R<T> build(CommonMessage message, T data) {
        return new R<>(message, data);
    }

    public static <T> R<T> build(String msg, CommonMessage message) {
        return new R<>(msg, message);
    }

    public static <T> R<T> build(CommonMessage message) {
        return new R<>(message, null);
    }

    @Override
    public int getCode() {
        return this.code;
    }

    @Override
    public String getMsg() {
        return this.msg;
    }

    public long getTimestamp() {
        return timestamp;
    }

    public T getData() {
        return data;
    }

    public R<T> setCode(int code) {
        this.code = code;
        return this;
    }

    public R<T> setMsg(String msg) {
        this.msg = msg;
        return this;
    }
}


